package com.qzxy.premiumhotelsystem.controller.common;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qzxy.premiumhotelsystem.common.annotation.LogExecutionTime;
import com.qzxy.premiumhotelsystem.common.constant.UserRoleConstant;
import com.qzxy.premiumhotelsystem.common.enums.LogLevel;
import com.qzxy.premiumhotelsystem.common.exception.SqlException;
import com.qzxy.premiumhotelsystem.domain.dto.GuestDTO;
import com.qzxy.premiumhotelsystem.domain.entity.Employees;
import com.qzxy.premiumhotelsystem.domain.entity.Guests;
import com.qzxy.premiumhotelsystem.domain.entity.Logs;
import com.qzxy.premiumhotelsystem.common.result.Result;
import com.qzxy.premiumhotelsystem.service.EmployeesService;
import com.qzxy.premiumhotelsystem.service.GuestsService;
import com.qzxy.premiumhotelsystem.service.LogsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: iQNRen
 * @Description: 导入导出数据列表
 * @Date: 2024/9/17 22:40 周二
 * @Version: 1.0
 */
//@SaCheckRole(type = UserRoleConstant.ADMIN,value = UserRoleConstant.ADMIN)
@RestController
@Tag(name = "通用接口",description = "excel操作")
@RequestMapping("excel")
public class ExcelController {
    @Resource
    private EmployeesService employeesService;
    @Resource
    private GuestsService guestsService;
    @Resource
    private LogsService logsService;

    @Operation(summary = "导出顾客列表", description = "导出顾客列表excel")
    @LogExecutionTime(message = "导出顾客列表",level = LogLevel.WARN)
    @GetMapping("guest/export")
    public void exportGuestsExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("顾客列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        List<Guests> userList = guestsService.allGuests();
        EasyExcel.write(response.getOutputStream(), Guests.class).sheet("顾客列表").doWrite(userList);

//        logsService.create("导出顾客列表");
    }

    @Operation(summary = "导入顾客列表", description = "导入顾客列表excel")
    @LogExecutionTime(message = "导入顾客列表",level = LogLevel.WARN)
    @PostMapping("guest/import")
    public Result importGuestsExcel(@RequestParam("file") MultipartFile file) throws IOException {
        List<Guests> guestList = EasyExcel.read(file.getInputStream()).head(Guests.class).sheet().doReadSync();
        // 处理导入的数据
        System.out.println(guestList);
        for (Guests guest : guestList) {
            try {
                guestsService.save(guest);
            } catch (SqlException e) {
                throw new SqlException("插入失败，违反唯一约束或主键冲突。");
            }
        }
//        logsService.create("导入顾客列表");
        return Result.ok("导入成功，数据量：" + guestList.size());
    }

    @Operation(summary = "导出员工列表", description = "导出员工列表excel")
    @LogExecutionTime(message = "导出员工列表",level = LogLevel.WARN)
    @GetMapping("employee/export")
    public void exportEmployeesExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("员工列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");


        List<Guests> userList = guestsService.allGuests();
        EasyExcel.write(response.getOutputStream(), Guests.class).sheet("员工列表").doWrite(userList);
//        logsService.create("导出员工列表");
    }

    @Operation(summary = "导入员工列表", description = "导入员工列表excel")
    @LogExecutionTime(message = "导入员工列表",level = LogLevel.WARN)
    @PostMapping("employee/import")
    public Result importEmployeesExcel(@RequestParam("file") MultipartFile file) throws IOException {
        List<Employees> employeeList = EasyExcel.read(file.getInputStream()).head(Guests.class).sheet().doReadSync();
        // 处理导入的数据
        System.out.println(employeeList);
        for (Employees employees : employeeList) {
            try {
                employeesService.save(employees);
            } catch (SqlException e) {
                throw new SqlException("插入失败，违反唯一约束或主键冲突。");
            }
        }
//        logsService.create("导入员工列表");
        return Result.ok("导入成功，数据量：" + employeeList.size());
    }


    @Operation(summary = "导出日志列表", description = "导出日志列表excel")
    @LogExecutionTime(message = "导出日志列表",level = LogLevel.WARN)
    @GetMapping("logs/export")
    public void exportLogsExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("日志列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");


        List<Logs> logList = logsService.allLogs("asc");
        EasyExcel.write(response.getOutputStream(), Logs.class).sheet("日志列表").doWrite(logList);

//        logsService.create("导出日志列表");
    }

    @Operation(summary = "导出日志列表_根据id", description = "导出日志列表excel_根据id")
    @LogExecutionTime(message = "导出日志列表_根据id",level = LogLevel.WARN)
    @GetMapping("logs/export/ids")
    public void exportLogsExcelByIds(HttpServletResponse response,@RequestParam List<Integer> ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("日志列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");

        System.out.println("ids"+ids);

        List<Logs> logList = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            System.out.println(ids.get(i));
            QueryWrapper<Logs> wrapper = new QueryWrapper<>();
            wrapper.eq("log_id",ids.get(i));
            logList.add(logsService.getOne(wrapper));
        }
        System.out.println(logList);
        EasyExcel.write(response.getOutputStream(), Logs.class).sheet("日志列表").doWrite(logList);

//        logsService.create("导出日志列表");
    }

    @Operation(summary = "导出历史订单", description = "导出历史订单excel")
    @LogExecutionTime(message = "导出历史订单",level = LogLevel.WARN)
    @GetMapping("history/export")
    public void exportHistoryExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("历史订单", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        List<GuestDTO> guestDTOS = guestsService.guestsForOrderStatusHistory();
        EasyExcel.write(response.getOutputStream(), GuestDTO.class).sheet("历史订单").doWrite(guestDTOS);

//        logsService.create("导出顾客列表");
    }
}

